package htdi.nutz.usermanager.module;

import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.mvc.view.HttpStatusView;

import htdi.nutz.usermanager.bean.User;

@At("/api/v1")
@IocBean
@Ok("json:full")
@Filters(@By(type = CheckSession.class, args = {"me", "/"}))
public class UserAdminModule {

    @Inject
    protected Dao dao;

    // https://gitee.com/how-to-do-it/user-manager/issues/ILBMM
    @GET
    public NutMap users(int page, int pageSize, String q) {
        Cnd cnd = null;
        if (!Strings.isBlank(q)) {
            cnd = Cnd.where("firstName", "like", q + "%").or("lastName", "like", q + "%");
        }
        List<User> users = dao.query(User.class, cnd, new Pager(page > 0 ? page : 1, pageSize > 0 ? pageSize : 10));
        NutMap re = new NutMap();
        re.put("data", users);
        re.put("recordsTotal", users.size());
        re.put("recordsFiltered", dao.count(User.class, cnd));
        return re;
    }

    // https://gitee.com/how-to-do-it/user-manager/issues/ILBNA
    @GET
    @At(value = {"/users/?", "/my/profile"})
    public NutMap getProfile(Long id, @Attr("me") User user) {
        if (id == null) {
            id = user.getId();
        }
        return new NutMap("user", dao.fetch(User.class, id));
    }

    // https://gitee.com/how-to-do-it/user-manager/issues/ILBO8
    @Ok("void")
    @PUT
    @At({"/users/?", "/users"})
    public Object update(Long id, @Attr("me") User me, @Param("..") User user) {
        if (id == null)
            id = me.getId();
        user.setId(id);
        int re = dao.update(user, "firstName|lastName");
        if (re < 1) {
            return HttpStatusView.HTTP_404;
        }
        return null;
    }

    // https://gitee.com/how-to-do-it/user-manager/issues/ILBOK
    @DELETE
    @At("/users/?")
    public Object delete(long id) {
        int re = dao.delete(User.class, id);
        if (re < 1) {
            return HttpStatusView.HTTP_404;
        }
        return new HttpStatusView(204);
    }
}
